<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" v-if="optType !='view'">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:md:mditem:add']"
        >新增</el-button>
        <ItemSelect ref="itemSelect" @onSelected="onItemSelected" > </ItemSelect>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:md:mditem:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>

    </el-row>
    <el-form ref="bomVersionForm" :model="bomVersionForm" :rules="rules" label-width="120px">
<!--    <el-form   ref="form" :model="form" :rules="rules" label-width="120px">-->


      <el-row>
        <el-col :span="4">
<!--          <el-form-item label="填写bom版本号" prop="bomVersion" label-width="30">
            <el-input
                v-model="bomVersionForm.bomVersion"
                placeholder="填写 BOM 版本"
                style="width: 100%; margin-bottom: 10px;"
            ></el-input>
          </el-form-item>-->
          <el-form-item label="bom版本号" prop="bomVersion" class="width:300px" >
            <el-input v-model="bomVersionForm.bomVersion" placeholder="请输入bom版本号" clearable style="width: 240px"
                      :disabled="true"
                        />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange">
<!--      <el-table-column label="bom版本">-->
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="物料编码" align="center" prop="bomItemCode" />
          <el-table-column label="物料名称" align="center" prop="bomItemName" :show-overflow-tooltip="true" />
<!--          <el-table-column label="一码多料类型" align="center" prop="bomItemName" :show-overflow-tooltip="true" />-->
          <el-table-column label="一码多料类型" min-width="120" align="left" key="multiFlag" prop="multiFlag"
                           :show-overflow-tooltip="true" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.item_multi_flag" :value="scope.row.multiFlag"/>
            </template>
          </el-table-column>
          <el-table-column label="规格" align="center" prop="bomItemSpec" :show-overflow-tooltip="true" />
          <el-table-column label="单位" width="60px" align="center" prop="unitOfMeasure" />
          <el-table-column label="使用比例" width="90px" align="center" prop="quantity" />
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="optType !='view'">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['mes:md:mditem:edit']"
              >修改</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['mes:md:mditem:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
<!--
      </el-table-column>-->

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

 <!-- 添加或修改产品BOM关系对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="BOM物料编码" prop="bomItemCode">
          <el-input v-model="form.bomItemCode" readonly placeholder="请输入BOM物料编码" />
        </el-form-item>
        <el-form-item label="BOM物料名称" prop="bomItemName">
          <el-input v-model="form.bomItemName" readonly placeholder="请输入BOM物料名称" />
        </el-form-item>
        <el-form-item label="BOM物料规格" prop="bomItemSpec">
          <el-input v-model="form.bomItemSpec" readonly type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="BOM物料单位" prop="unitOfMeasure">
          <el-input v-model="form.unitOfMeasure" readonly placeholder="请输入BOM物料单位" />
        </el-form-item>
        <el-form-item label="物料使用比例" prop="quantity">
          <el-input-number  :precision="4" :step="0.1" :min="0"  v-model="form.quantity" placeholder="请输入物料使用比例" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listBom, getBom, delBom, addBom, updateBom } from "@/api/mes/md/bom";
import ItemSelect from "@/components/itemSelect/index.vue";

export default {
  name: "Bom",
  dicts: ['sys_yes_no', 'mes_item_product','md_phase_code','item_multi_flag'],
  components: { ItemSelect },
  props: {
    optType: String,
    itemId: String,
    tabName: String, // 新增的属性
    bomVersion: String,
    bomVersionId: String
  },
  data() {
    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品BOM关系表格数据
      bomList: [],
      // 版本输入框的值
      // bomVersion: '', // 用于存储当前标签页的版本信息
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: this.itemId,
        bomVersion:this.bomVersion,
        bomItemId: null,
        bomItemCode: null,
        bomItemName: null,
        bomItemSpec: null,
        unitOfMeasure: null,
        quantity: null,
        enableFlag: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        bomVersionId: this.bomVersionId,
      },
      // 表单参数
      form: {},
      bomVersionForm:{
        bomVersion:this.bomVersion,
        bomVersionId:this.bomVersionId
      },
      // 表单校验
      rules: {
        quantity: [
          { required: true, message: "物料使用比例不能为空", trigger: "blur" }
        ],
        bomVersion: [
          { required: true, message: "bom版本号不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    // 监听 bomVersion 和 bomVersionId 的变化，重新加载数据
    bomVersion(newVal) {
      this.queryParams.bomVersion = newVal;
      this.bomVersionForm.bomVersion = newVal;
      this.$nextTick(() => {
        // 确保 DOM 渲染完成后执行的操作
        // console.log('bomVersionForm updated:', this.bomVersionForm);
      });
      this.getList();
    },
    bomVersionId(newVal) {
      this.queryParams.bomVersionId = newVal;
      this.bomVersionForm.bomVersionId = newVal;
      this.$nextTick(() => {
        // 确保 DOM 渲染完成后执行的操作
        // console.log('bomVersionForm updated:', this.bomVersionForm);
      });
      this.getList();
    },
    // 监听 itemId 的变化，重新加载数据
    itemId(newVal) {
      // console.log('itemId newVal-', newVal);
      if (newVal) {
        this.queryParams.itemId = newVal;
        this.getList();
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产品BOM关系列表 */
    getList() {
      this.loading = true;
      this.queryParams.bomVersion=this.tabName;
      this.queryParams.bomVersionId=this.bomVersionId;
      // console.log('child list---this.tabName ',this.tabName);
      // console.log('child list---this.bomVersionId ',this.bomVersionId);
      this.bomVersionForm.bomVersion=this.tabName;
      this.bomVersionForm.bomVersionId=this.bomVersionId;

      listBom(this.queryParams).then(response => {
        this.bomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bomId: null,
        itemId: null,
        bomItemId: null,
        bomItemCode: null,
        bomItemName: null,
        bomItemSpec: null,
        unitOfMeasure: null,
        itemOrProduct: null,
        quantity: null,
        enableFlag: 'Y',
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tabName: this.tabName, // 确保表单数据包含当前标签页名称
        bomVersion: null,
        bomVersionId: null,
        multiFlag:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bomId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.tabName = this.tabName; // 设置表单中的 tabName
      this.$refs.itemSelect.showFlag = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const bomId = row.bomId || this.ids;
      getBom(bomId).then(response => {
        this.form = response.data;
        this.form.tabName = this.tabName; // 设置表单中的 tabName
        this.open = true;
        this.title = "修改产品BOM关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 根据表单中的 id 决定是新增还是修改
          if (this.form.bomId) {
            updateBom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bomIds = row.bomId || this.ids;
      this.$modal.confirm(`是否确认删除产品BOM关系编号为"${bomIds}"的数据项？`).then(() => {
        delBom(bomIds).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        });
      }).catch(() => {});
    },
    // 物料选择弹出框
    onItemSelected(obj) {
      this.form.itemId = this.itemId;
      // console.log('--onItemSelected form bomVersion--',this.bomVersionForm);
      if (obj != undefined && obj != null) {
        obj.forEach(element => {
          // console.log('onItemSelected element--',element)
          this.form.bomItemId = element.itemId;
          this.form.bomItemCode = element.itemCode;
          this.form.bomItemName = element.itemName;
          this.form.bomItemSpec = element.specification;
          this.form.unitOfMeasure = element.unitOfMeasure;
          this.form.itemOrProduct = element.itemOrProduct;
          this.form.quantity = 1;
          this.form.enableFlag = 'Y';
          this.form.tabName = this.tabName; // 设置表单中的 tabName
          this.form.bomVersion=this.bomVersionForm.bomVersion;
          this.form.bomVersionId = this.bomVersionId
          addBom(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.getList();
          });
        });
      }
    }
  }
};
</script>
